package com.ponhu.ea2.stockcenter.config;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.google.common.collect.Lists;
import com.ponhu.ea2.stockcenter.service.bms.StockCheckService;
import com.ponhu.ea2.stockcenter.vo.JuWoImportData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class JuWoImportDataListenter extends AnalysisEventListener<JuWoImportData> {

    private final AtomicInteger count = new AtomicInteger(0);
    private final List<JuWoImportData> juWoList = Lists.newArrayList();
    private final List<CompletableFuture> futureList = Lists.newArrayList();

    @DubboReference(version = "1.0.0", check = false)
    private StockCheckService stockCheckService;

    @Override
    public void invoke(JuWoImportData juWoImportData, AnalysisContext analysisContext) {
        if (StringUtils.isEmpty(juWoImportData.getInventoryCode())) return;
        int incrementAndGet = count.incrementAndGet();
        juWoList.add(juWoImportData);
        if (juWoList.size() == 2000) {
            List<JuWoImportData> juWoSaveList = Lists.newArrayList();
            juWoSaveList.addAll(juWoList);
            futureList.add(CompletableFuture.runAsync(() -> {
//                boolean juWoImportDataSave = stockCheckService.juWoImportDataSave(juWoSaveList);
//                log.info("保存巨沃导入数据 ===>> {} ===>> {} ===>> {}",
//                        Thread.currentThread().getName(), incrementAndGet, juWoImportDataSave);
            }));
            juWoList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (juWoList.size() > 0) {
            futureList.add(CompletableFuture.runAsync(() -> {
//                boolean juWoImportDataSave = stockCheckService.juWoImportDataSave(juWoList);
//                log.info("保存巨沃导入数据 ===>> {} ===>> {} ===>> {}",
//                        Thread.currentThread().getName(), count.get(), juWoImportDataSave);
            }));
        }
        count.set(0);
        juWoList.clear();
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();
        log.info("保存巨沃导入数据完成");
    }

}
